package com.qubuyer.core.http

import com.google.gson.Gson
import com.qubuyer.core.ext.application
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory

/**
 * Created by kyle on 2017/12/3.
 */
class Api private constructor() {

    private val mRetrofit: Retrofit = Retrofit.Builder()
//            .baseUrl(application.configBaseUrl())
            .baseUrl("https://api.qubuyer.com/")
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(application.gson() ?: Gson()))
//            .addConverterFactory(GsonConverterFactory.create())
            .client(OkHttpUtil.util.okHttpClient)
            .build()

    private val serviceMap: HashMap<String, Any> = HashMap()

    companion object {
        private var mInstance: Api? = null

        /**
         * 单例模式
         *
         * @return
         */
        @JvmStatic
        fun getInstance(): Api {
            if (mInstance == null) {
                synchronized(Api::class.java) {
                    if (mInstance == null) {
                        mInstance = Api()
                    }
                }
            }
            return mInstance!!
        }
    }

    fun <T> create(clazz: Class<T>): T {
        val name = clazz.name
        val service = serviceMap[name] as T?
        return service ?: mRetrofit.create(clazz).also { serviceMap[name] = it as Any }
    }
}